<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form id="cookieForm" action="#">
        <h1>Enter your name: <input type="text" id="nameField"></h1>
    </form>
    <script>
        window.addEventListener("load", initForm, false);

        function initForm() {
            var userName = "";
            if (document.cookie != "") {
                userName = document.cookie.split("=")[1];

            }
            document.getElementById("nameField").value = userName;
            document.getElementById("nameField").onblur = setCookie;
            document.getElementById("cookieForm").onsubmit = setCookie;
        }
        //设置cookie
        function setCookie() {
            var expireDate = new Date();
            expireDate.setMonth(expireDate.getMonth() + 6);
            var username = document.getElementById("nameField").value;
            //alert(expireDate.toGMTString());
            document.cookie = "userName=" + username + ";expires=" + expireDate.toGMTString();
            document.getElementById("nameField").blur();
            return false;
        }
    </script>
</body>

</html>